package root.electronclass.electronclass.personal.activity.model

import androidx.lifecycle.*
import root.electronclass.electronclass.mvp.entity.MoralScoreRecord
import root.electronclass.electronclass.ext.CoroutineExceptionHandler
import root.electronclass.electronclass.personal.PersonRepository
import kotlinx.coroutines.launch

/**
 *@ClassName TODO
 *@Description TODO
 *@Author caofc
 *@Date 2023/3/24 20:59
 */
class CharacterModel : ViewModel() {

    private val _data = MediatorLiveData<Pair<Int, List<MoralScoreRecord>>>()
    val data: LiveData<Pair<Int, List<MoralScoreRecord>>> = _data

    private val pageIndex = MutableLiveData(1)

    private var type: Int = 1// 4:竞赛德育
    private var competitionId: Long = 1

    init {
        load(page = 1)
    }


    fun load(type: Int = this.type, competitionId: Long= 1 ,page: Int = (pageIndex.value ?: 1) + 1) {
        this.type = type
        this.competitionId = competitionId
        pageIndex.value = page
        loadData(type,competitionId)
    }

    private fun loadData(type: Int, competitionId: Long) {
        viewModelScope.launch(CoroutineExceptionHandler() { pageIndex.value = ((pageIndex.value ?: 1) - 1).coerceAtLeast(1) }) {
            _data.value = pageIndex.value!! to PersonRepository.examPage1(pageIndex.value!!, type,competitionId)
            pageIndex.value = (pageIndex.value ?: 1) + 1
        }
    }
}